extends Node2D

# 关卡管理器
class_name LevelManager

# 关卡类型枚举
enum LevelType {
	TUTORIAL,  # 教程关卡
	DESERT,    # 沙漠关卡
	FOREST,    # 森林关卡
	SNOW       # 雪山关卡
}

# 当前关卡类型
@export var current_level_type: LevelType = LevelType.TUTORIAL

# 关卡难度
@export var level_difficulty: int = 1

# 关卡时间限制（秒）
@export var level_time_limit: float = 300.0

# 关卡计时器
var level_timer: float = 0.0

# 是否已完成关卡
var level_completed: bool = false

# 是否已失败关卡
var level_failed: bool = false

# 玩家引用
var player: Node2D

# 敌人生成器引用
var enemy_spawner: Node2D

# UI引用
var ui: Node2D

# 关卡背景引用
var background: Node2D

# 信号
signal level_completed_signal
signal level_failed_signal
signal level_time_updated(time_left: float)

func _ready():
	# 获取玩家引用
	player = get_tree().get_first_node_in_group("player")
	
	# 获取敌人生成器引用
	enemy_spawner = get_node_or_null("EnhancedEnemySpawner")
	
	# 获取UI引用
	ui = get_tree().get_first_node_in_group("ui")
	
	# 获取背景引用
	background = get_node_or_null("Background")
	
	# 设置关卡
	setup_level()

func _process(delta):
	# 更新关卡计时器
	if not level_completed and not level_failed:
		level_timer += delta
		emit_signal("level_time_updated", level_time_limit - level_timer)
		
		# 检查是否超时
		if level_timer >= level_time_limit:
			complete_level()

func setup_level():
	# 根据关卡类型设置背景
	if background:
		match current_level_type:
			LevelType.TUTORIAL:
				background.texture = load("res://asset/background/forest/image_fx_.jpg")
			LevelType.DESERT:
				background.texture = load("res://asset/background/desert/image_fx_.jpg")
			LevelType.FOREST:
				background.texture = load("res://asset/background/forest/image_fx_.jpg")
			LevelType.SNOW:
				background.texture = load("res://asset/background/snowmountain/image_fx_.jpg")
	
	# 设置敌人生成器
	if enemy_spawner:
		enemy_spawner.level_type = current_level_type
		enemy_spawner.difficulty = level_difficulty
	
	# 重置计时器
	level_timer = 0.0
	level_completed = false
	level_failed = false
	
	# 通知UI
	if ui:
		ui.update_level_info(current_level_type, level_difficulty)

func complete_level():
	if level_completed:
		return
	
	level_completed = true
	print("关卡完成!")
	
	# 停止敌人生成
	if enemy_spawner:
		enemy_spawner.stop_spawning()
	
	# 发送完成信号
	emit_signal("level_completed_signal")
	
	# 延迟后加载下一关
	await get_tree().create_timer(3.0).timeout
	load_next_level()

func fail_level():
	if level_failed:
		return
	
	level_failed = false
	print("关卡失败!")
	
	# 停止敌人生成
	if enemy_spawner:
		enemy_spawner.stop_spawning()
	
	# 发送失败信号
	emit_signal("level_failed_signal")
	
	# 延迟后重新加载当前关卡
	await get_tree().create_timer(3.0).timeout
	reload_current_level()

func load_next_level():
	# 根据当前关卡类型和难度决定下一关
	var next_level_type = current_level_type
	var next_difficulty = level_difficulty
	
	# 增加难度或切换关卡类型
	if level_difficulty < 5:  # 每种关卡类型有5个难度
		next_difficulty += 1
	else:
		next_difficulty = 1
		next_level_type = (next_level_type + 1) % 4  # 循环切换关卡类型
	
	# 加载下一关
	var next_level_scene = ""
	
	match next_level_type:
		LevelType.TUTORIAL:
			next_level_scene = "res://TutorialLevel.tscn"
		LevelType.DESERT:
			next_level_scene = "res://DesertLevel.tscn"
		LevelType.FOREST:
			next_level_scene = "res://ForestLevel.tscn"
		LevelType.SNOW:
			next_level_scene = "res://SnowLevel.tscn"
	
	# 保存玩家状态
	var player_stats = {}
	if player:
		player_stats = {
			"health": player.current_health,
			"max_health": player.max_health,
			"speed": player.speed,
			"damage": player.damage,
			"experience": player.experience,
			"level": player.level
		}
	
	# 切换场景
	get_tree().change_scene_to_file(next_level_scene)
	
	# 在下一帧恢复玩家状态
	await get_tree().process_frame
	
	# 获取新场景中的玩家和关卡管理器
	var new_player = get_tree().get_first_node_in_group("player")
	var new_level_manager = get_tree().get_first_node_in_group("level_manager")
	
	# 恢复玩家状态
	if new_player and not player_stats.is_empty():
		new_player.current_health = player_stats.health
		new_player.max_health = player_stats.max_health
		new_player.speed = player_stats.speed
		new_player.damage = player_stats.damage
		new_player.experience = player_stats.experience
		new_player.level = player_stats.level
	
	# 设置新关卡的难度
	if new_level_manager:
		new_level_manager.current_level_type = next_level_type
		new_level_manager.level_difficulty = next_difficulty

func reload_current_level():
	# 重新加载当前关卡
	var current_level_scene = ""
	
	match current_level_type:
		LevelType.TUTORIAL:
			current_level_scene = "res://TutorialLevel.tscn"
		LevelType.DESERT:
			current_level_scene = "res://DesertLevel.tscn"
		LevelType.FOREST:
			current_level_scene = "res://ForestLevel.tscn"
		LevelType.SNOW:
			current_level_scene = "res://SnowLevel.tscn"
	
	# 切换场景
	get_tree().change_scene_to_file(current_level_scene)
	
	# 在下一帧设置关卡难度
	await get_tree().process_frame
	
	# 获取新场景中的关卡管理器
	var new_level_manager = get_tree().get_first_node_in_group("level_manager")
	
	# 设置新关卡的难度
	if new_level_manager:
		new_level_manager.current_level_type = current_level_type
		new_level_manager.level_difficulty = level_difficulty
